define(['template', 'jquery' ,'utils'], (template) => {
  class Header {
    constructor () {
      this.loadHTML().then(()=>{
		   this.Logout()
		   this.Login()
		   this.calcCartCount()
	  })
    }
    loadHTML () {
		return new Promise((resolve,reject)=>{
			$('.nav-header').load('/html/modules/header.html',()=>{
				resolve()
			}) 
		})
		}
	Logout (){
		 var username = utils.getCookie('name')
		 $('#logout').on('click', function(){
		 	if(confirm('确定要退出吗？')){
				utils.setCookie('name', '', {expires:-1, path:'/'})
		 		$("#loginIn").removeClass('hider')
		 		$("#register").removeClass('hider')
		 		$(".login-in").addClass('hider')
		 		$("#logout").addClass('hider')
		 	}
		 })
	}
	calcCartCount () {
	  let count = 0
	  let cart = localStorage.getItem('cart')
	  if (cart) {
	    cart = JSON.parse(cart)
	    count = cart.reduce((num, shop) => {
	      num += shop.count
	      return num
	    }, 0)
	  }
	  $('#cart-num').html(count)
	}
	Login (){
			 var Submit= $('#submit')
			 var nameInput = $('#name')
			 var pwdInput = $('#pwd')
			 var username = utils.getCookie('name')
			 
			 if(username){
				 $("#loginIn").addClass('hider')
				 $("#register").addClass('hider')
				 $("#login-in").removeClass('hider')
				 $("#logout").removeClass('hider')
			 }
			  // 使用事件监听
			  Submit.on('click', function (e) {
			    // 在事件监听里用e.preventDefault()
			    // 事件绑定里阻止默认行为用return false或者window.event.returnValue = false
				
				e.preventDefault()
			    const name = nameInput.val()
			    const pwd = pwdInput.val()
			    utils.post('http://localhost/2stage/2exsesize/day25exsesize/el-shop/api/user/login.php', { name, pwd }, resp => {
			      if (resp.code === 200) {
			        utils.setCookie('name', name, { expires: 7, path: '/' })
					alert(resp.body.msg + '，即将回到首页')
			        // replace是替换路径，也就是页面跳转
			        location.replace('/index.html')
			      } else {
			        alert(resp.body.msg)
			      }
			    })
			  })
			}
		  }
   return new Header()
})
